//
//  EditRouteController.m
//  Cycling
//
//  Created by 迟国强 on 2023/4/5.
//

#import "EditRouteController.h"
#import "RouteNameMessageCell.h"
#import "HeightTableCell.h"
#import "RouteTypeTableCell.h"
#import "RouteImageTableCell.h"
#import "RouteShareTableCell.h"
#import "MapRequest.h"
#import "CyclingRequest.h"

#import <MobileCoreServices/MobileCoreServices.h>
#import "RouteRequest.h"

#import "Cycling-Swift.h"

@interface EditRouteController ()<UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate>

@property (nonatomic, strong) NSMutableArray *dataArray;  // 列表数据
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *imageNames;
@property (nonatomic) NSInteger imageUploadNums;

@end

@implementation EditRouteController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.title = CycLocalizedString(@"Edit Route", @"编辑路线");
    self.view.backgroundColor = rgbHex(0xF8F8F8, 1);
    self.dataArray = [NSMutableArray array];
    [self.view addSubview:self.tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.bottom.equalTo(@0);
    }];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 202)];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.clipsToBounds = YES;
    imageView.backgroundColor = UIColor.clearColor;
    [imageView sd_setImageWithURL:[NSURL URLWithString:self.editModel.detailModel.fulllineimg]];
    self.tableView.tableHeaderView = imageView;
    
    UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 94)];
    
    UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    saveBtn.frame = CGRectMake(30, 10, SCREEN_W - 60, 54);
    saveBtn.backgroundColor = rgb(30, 214, 194);
    [saveBtn setTitle:CycLocalizedString(@"Save route", @"保存路线") forState:UIControlStateNormal];
    [saveBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    saveBtn.layer.cornerRadius = 27;
    saveBtn.layer.masksToBounds = YES;
    [saveBtn addTarget:self action:@selector(saveButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [footer addSubview:saveBtn];
    self.tableView.tableFooterView = footer;
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"nav_back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(backButtonAction)];
    if(self.isAdd) {
        self.title = CycLocalizedString(@"Ride details", "骑行详情");
    }
    
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
}

- (void)saveButtonAction
{
    if(self.editModel.name.length == 0) {
        [self showHudTipStr:CycLocalizedString(@"Input route name", @"请输入路线名称")];
        return;
    }
    [self showLoadingViewWithText:nil];
    self.imageUploadNums = 0;
    [self updateImagesComplete:^{
        [self addPersonalRoute];
    }];
}

- (void)updateImagesComplete:(void(^)(void))complete
{
    if(self.editModel.images.count <= self.imageUploadNums) {
        if(complete) {
            complete();
        }
        return;
    }
    UIImage *iconImage = self.editModel.images[self.imageUploadNums];
    if([iconImage isKindOfClass:[NSString class]]) {
        [self.imageNames addObject:iconImage];
        self.imageUploadNums++;
        [self updateImagesComplete:complete];
        return;
    }
    self.imageUploadNums++;
    NSData *file = UIImageJPEGRepresentation(iconImage, 1);
    [CyclingRequest uploadImageWithFileData:file complete:^(NSString *imagePath) {
        if(imagePath) {
            [self.imageNames addObject:imagePath];
        }
        [self updateImagesComplete:complete];
    }];
}

- (void)addPersonalRoute
{
    if(self.editModel.name.length == 0) {
        [self showHudTipStr:@"请输入路线名称"];
        return;
    }
    if(self.editModel.contentString.length == 0) {
        self.editModel.contentString = @"";
    }
    
    NSString *imageName = [self.imageNames componentsJoinedByString:@","];
    NSDictionary *params = @{@"id" : self.isAdd ? @(self.editModel.cid) : @(self.editModel.detailModel.routeId), @"name" : self.editModel.name, @"introduce" : self.editModel.contentString, @"bicycleType" : @(self.editModel.cycleType), @"ground" : @(self.editModel.routeType), @"imgs" : imageName, @"share" : @(self.editModel.facebookShared ? 1 : 2), @"linestatus" : @(self.editModel.routeSave ? 1 : 2)};
    self.tableView.userInteractionEnabled = NO;
//    NSString *sharedImageUrlStr = self.imageNames.count > 0 ? self.imageNames.firstObject : self.editModel.detailModel.fulllineimg;
    NSMutableArray *sharedImageNames = [NSMutableArray arrayWithObject:self.editModel.detailModel.fulllineimg];
    [sharedImageNames addObjectsFromArray:self.imageNames];
    if(self.isAdd){
        [RouteRequest postAddPersonalRouteWithParams:params result:^(BOOL success, NSDictionary *data, NSString *reason) {
            [self removeLoadingView];
            if(success) {
                [HUDHelper showHudTipStr:reason];
                [self.navigationController popToRootViewControllerAnimated:YES];
                [self facebookSharedWithImageNames:sharedImageNames];
            }
            self.tableView.userInteractionEnabled = YES;
        }];
    }else {
        [RouteRequest postEidtPersonalRouteWithParams:params result:^(BOOL success, NSDictionary *data, NSString *reason) {
            [self removeLoadingView];
            if(success) {
                [HUDHelper showHudTipStr:reason];
                [self.navigationController popToRootViewControllerAnimated:YES];
                [self facebookSharedWithImageNames:sharedImageNames];
            }
            self.tableView.userInteractionEnabled = YES;
        }];
    }
}

- (NSMutableArray *)imageNames
{
    if(!_imageNames) {
        _imageNames = [NSMutableArray array];
    }
    return _imageNames;
}

#pragma mark - tableView delegate datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 6;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        RouteNameMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RouteNameMessageCell"];
        cell.editModel = self.editModel;
        cell.nameChangedBlock = ^(NSString *name) {
            self.editModel.name = name;
        };
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    } else if (indexPath.row == 1) {
        RouteInfoMessageCell *messageCell = [tableView dequeueReusableCellWithIdentifier:@"RouteInfoMessageCell"];
        
        messageCell.editModel = _editModel;
        
        return messageCell;
        
    } else if (indexPath.row == 2) {
        HeightTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HeightTableCell"];
        cell.heightModel = self.editModel.detailModel.highly;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
//    else if (indexPath.row == 3) {
//        RouteTypeTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RouteTypeTableCell"];
//        cell.editModel = self.editModel;
//        cell.selectionStyle = UITableViewCellSelectionStyleNone;
//        return cell;
//    }
    else if (indexPath.row == 3) {
        RouteTypeTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RouteTypeTableCell"];
        cell.groundEditModel = self.editModel;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    } else if (indexPath.row == 4) {
        RouteImageTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RouteImageTableCell"];
        cell.editModel = self.editModel;
        cell.willAddImageBlock = ^{
            [self addImage];
        };
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    } else {
        RouteShareTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RouteShareTableCell"];
        cell.facebookShared = self.editModel.facebookShared;
        cell.routeSaved = self.editModel.routeSave;
        cell.valueChangedBlock = ^(NSInteger type, BOOL value) {
            if(type == 0) {
                self.editModel.facebookShared = value;
            } else if(type == 1) {
                self.editModel.routeSave = value;
            }
        };
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return 120;
    } else if(indexPath.row == 1) {
        return 120;
    } else if (indexPath.row == 2) {
        return 225;
    }
//    else if (indexPath.row == 3) {
//        return 125;
//    }
    else if (indexPath.row == 3) {
        return 125;
    } else if (indexPath.row == 4) {
        return 187;
    } else {
        return 271;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = rgbHex(0xF8F8F8, 1);
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        } else {
            // Fallback on earlier versions
        }
        if (@available(iOS 11.0, *) ) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"RouteNameMessageCell" bundle:nil] forCellReuseIdentifier:@"RouteNameMessageCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"HeightTableCell" bundle:nil] forCellReuseIdentifier:@"HeightTableCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"RouteTypeTableCell" bundle:nil] forCellReuseIdentifier:@"RouteTypeTableCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"RouteImageTableCell" bundle:nil] forCellReuseIdentifier:@"RouteImageTableCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"RouteShareTableCell" bundle:nil] forCellReuseIdentifier:@"RouteShareTableCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"RouteInfoMessageCell" bundle:nil] forCellReuseIdentifier:@"RouteInfoMessageCell"];

    }
    return _tableView;
}


#pragma mark - 分享图片
- (void)facebookSharedWithImageNames:(NSArray<NSString *> *)imageNames
{
    if(!self.editModel.facebookShared) {
        return;
    }

    NSMutableArray *sharedImageNames = [NSMutableArray array];
    for(NSString *imageName in imageNames) {
        if(![imageName hasPrefix:@"http"]) {
            [sharedImageNames addObject:[NSString stringWithFormat:@"%@%@", BaseUrl, imageName]];
        } else {
            [sharedImageNames addObject:imageName];
        }
    }
    
//    [self showLoadingViewWithText:@""];
    [CSFacebookShareManager sharedWithImageStrings:sharedImageNames fromViewController:self complete:^(BOOL success, BOOL cancel) {
//        [self removeLoadingView];
        if(!success && !cancel) {
            [self showHudTipStr: CycLocalizedString(@"Shared fail", @"分享失败")];
        }
    }];
}

@end

/**
 添加图片类
 */
@implementation EditRouteController (AddImage)

- (void)addImage
{
    UIAlertController *alertPhoto = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    alertPhoto.popoverPresentationController.sourceView = self.view;
    alertPhoto.popoverPresentationController.sourceRect = CGRectMake(0,SCREEN_W/2,SCREEN_W,SCREEN_H);

    [self presentViewController:alertPhoto animated:YES completion:nil];
//        __weak typeof(self)weakSelf = self;
    
    UIAlertAction *camaraSeleect = [UIAlertAction actionWithTitle:CycLocalizedString(@"Camera", @"拍照") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self takePhotos];
    }];
    [alertPhoto addAction:camaraSeleect];
    
    UIAlertAction *pictureSelect = [UIAlertAction actionWithTitle:CycLocalizedString(@"Gallery", @"从手机相册选取") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self selectPhoto];
    }];
    [alertPhoto addAction:pictureSelect];
    
    UIAlertAction *alertCanle = [UIAlertAction actionWithTitle:CycLocalizedString(@"Cancel", @"取消") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alertPhoto addAction:alertCanle];
}

//去拍照
- (void)takePhotos {
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
//        DLog(@"%@",granted ? @"相机准许":@"相机不准许");
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!granted) {
                [self nounShow:0];
            } else {
                UIImagePickerController *imgController = [[UIImagePickerController alloc] init];
                imgController.sourceType = UIImagePickerControllerSourceTypeCamera;
                imgController.cameraDevice = UIImagePickerControllerCameraDeviceRear;
                NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
                [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
                imgController.mediaTypes = mediaTypes;
                imgController.delegate = self;
                imgController.allowsEditing = YES;
                [self presentViewController:imgController
                                   animated:YES
                                 completion:^(void) {
//                    DLog(@"Picker View Controller is presented");
                }];
            }
        });
    }];
}
//去选照片
- (void)selectPhoto {
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (status != PHAuthorizationStatusAuthorized) {
                [self nounShow:1];
            } else {
                UIImagePickerController *imgController = [[UIImagePickerController alloc] init];
                imgController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
                [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
                imgController.mediaTypes = mediaTypes;
                imgController.delegate = self;
                imgController.allowsEditing = YES;
                [self presentViewController:imgController
                                   animated:YES
                                 completion:^(void) {
                }];
            }
        });
    }];
}

- (void)nounShow:(NSInteger)type {
    NSString *message;
    if (type == 0) {
        message = CycLocalizedString(@"Please go to Settings ->Privacy ->Camera Authorization Application for photo permissions", @"请前往设置->隐私->相机授权应用拍照权限");
    } else {
        message = CycLocalizedString(@"Please go to Settings ->Privacy ->Photo Authorization Application for photo permissions", @"请前往设置->隐私->照片授权应用拍照权限");
    }
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:CycLocalizedString(@"Note", @"提示") message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * sureAction = [UIAlertAction actionWithTitle:CycLocalizedString(@"Confirm", @"确认") style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action) {
    }];
    [alert addAction:sureAction];
    [self presentViewController:alert animated:true completion:nil];
}

#pragma mark - UIImagePicker Delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    UIImage *portraitImg = [info objectForKey:UIImagePickerControllerEditedImage];
    [self dismissViewControllerAnimated:YES completion:nil];
    if (portraitImg != nil) {
        [self.editModel.images addObject:portraitImg];
        [self.tableView reloadData];
//        NSData *file = UIImageJPEGRepresentation(portraitImg, 1);
//        [self showHudTipStr:nil];
//        [MineRequest uploadavatarWithFile:file type:nil result:^(NSDictionary * _Nonnull ret) {
//
//        }];

    }


}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
}

#pragma mark - UIGestureRecognizer Delegate Methods
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    [self backButtonAction];
    return NO;
}

@end

/**
 返回提醒
 */
@implementation EditRouteController (AlertOfBack)

- (void)backButtonAction
{
    [self showAlertWithTitle:CycLocalizedString(@"Discard saving?", @"放弃添加?") message:nil leftTitle:CycLocalizedString(@"Yes", "是的") leftStyle:UIAlertActionStyleDefault leftBlock:^{
        [self.navigationController popToRootViewControllerAnimated:YES];
    } rightTitle:CycLocalizedString(@"No", "不") rightStyle:UIAlertActionStyleDestructive rightBlock:^{
        
    }];
}

@end
